package com.example.chatroom.api;

import com.example.chatroom.component.OnlineUserManger;
import com.example.chatroom.model.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;

@Component
public class WebSocketAPI extends TestWebSocketAPI{
    @Autowired
    private OnlineUserManger onlineUserManger;

    @Autowired
    private MessageSessionMapper messageSessionMapper;

    @Autowired
    private MessageMapper messageMapper;

    private ObjectMapper objectMapper=new ObjectMapper();


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //这个方法会在 websocket 连接成功后自动调用
        System.out.println("websocket 连接成功");
        User user=(User) session.getAttributes().get("user");
        System.out.println("userId = "+user.getUserId());
        if (user==null){
            return;
        }
        onlineUserManger.online(user.getUserId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //这个方法会在 websocket 收到消息后，自动调用
        System.out.println("websocketAPI 收到消息"+message.toString());
        //获取当前用信息
        User user=(User) session.getAttributes().get("user");
        if (user==null){
            System.out.println("user is null");
            return;
        }
        //对请求进行解析,得到的时json的对象 需要引入objectMapper
        MessageRequest req= objectMapper.readValue(message.getPayload(),MessageRequest.class);
        if (req.getType().equals("message")) {
            //进行消息转发
            transferMessage(user,req);

        }else {
            System.out.println("req 有误");
        }
    }
    private void transferMessage(User fromUser,MessageRequest req) throws IOException {
        //先构造MessageResponse对象
        MessageResponse resp=new MessageResponse();
        resp.setType("message");
        resp.setFromId(fromUser.getUserId());
        resp.setFromName(fromUser.getUsername());
        resp.setSessionId(req.getSessionId());
        resp.setContent(req.getContent());
        //把Java对象转换成字符串,需要抛出异常
        String respJson=objectMapper.writeValueAsString(resp);
        System.out.println("respJson:"+respJson);
        //得到sessionId的查询到MessageSession有哪些用户
        List<Friend> friends= messageSessionMapper.getFriendsBySessionId(req.getSessionId(), fromUser.getUserId());
        //此时的到的friend是将自己的id给去除了，但是消息发送的时候还得给自己发一份
        Friend myself=new Friend();
        myself.setFriendId(fromUser.getUserId());
        myself.setFriendName(fromUser.getUsername());
        friends.add(myself);
        //遍历列表，给每个用户都发送一份响应消息
        for (Friend friend :friends) {
            //得到每个用户的userId就可以通过Websocket就可以的到每个用户的WebsocketSession
            WebSocketSession webSocketSession= onlineUserManger.getSession(friend.getFriendId());
            if (webSocketSession == null) {
                //该用户不在线
                continue;
            }
            webSocketSession.sendMessage(new TextMessage(respJson));
        }

        //将转发的消息插入到数据库里面
        Message message=new Message();
        message.setFromId(fromUser.getUserId());
        message.setSessionId(req.getSessionId());
        message.setContent(req.getContent());
        //自增主键和时间在数据库的时候就自动生成了
        messageMapper.add(message);
    }
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //这个方法会在连接出现异常后,自动调用
        System.out.println("websocketAPI 连接异常");
        User user=(User) session.getAttributes().get("user");
        System.out.println("userId = "+user.getUserId());
        if (user==null){
            return;
        }

        onlineUserManger.offOnline(user.getUserId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //这个方法会在正常关闭后,自动调用
        System.out.println("websocketAPI  正常关闭");
        User user=(User) session.getAttributes().get("user");
        System.out.println("userId = "+user.getUserId());
        if (user==null){
            return;
        }
        onlineUserManger.offOnline(user.getUserId(), session);
    }
}
